package com.tundriki.pref;

import java.util.Arrays;

import javax.microedition.khronos.opengles.GL10;

public class CardHolder {
	final float cardPlaces[];
	Card cards[];
	
	public CardHolder(int maxPlaces) {
		super();
		cardPlaces = new float[maxPlaces*3];
		cards = new Card[maxPlaces];

		for(int i=0;i<maxPlaces;i++) {
			cards[i] = null;
			cardPlaces[i*3] = cardPlaces[i*3+1] = cardPlaces[i*3+2] = 0.0f;  
		}
	}
		
	public CardHolder(float[] places) {
		this(places.length/3);
		for(int i=0;i<places.length && i<cardPlaces.length; i++)
				cardPlaces[i] = places[i];
	}
	
	public void draw(GL10 gl) {
		for(int i=0; i<cards.length ; i++) {
			if (cards[i]!=null) {
			float x = cardPlaces[i*3],
				  y = cardPlaces[i*3+1],
				  z = cardPlaces[i*3+2];
				if (! cards[i].samePosition(x,y,z))
					cards[i].moveTo(x, y, z);
				cards[i].draw(gl);
			}
		}
	}
	
	public void addCard(Card card) {
		int i=0;
		if (card==null)
			return;
		while(i<cards.length && cards[i]!=null) 
			i++;
		if (i<cards.length)
			cards[i] = card;
		
	}
	
	public void deleteCard(Card card) {
		int i=0;
		if (card==null)
			return;		
		while(i<cards.length && !cards[i].name.equals(card.name))
			i++;
		while(i<(cards.length-1)) {
			cards[i] = cards[i+1];
			i++;
		}
		if (i<cards.length)
			cards[i] = null;
	}
	public void sortCards() {
		Arrays.sort(cards, new CardComparator());
	}
	
	public Card cardFromScreenEvent(float[][] coord) {
	Card rv = null;
		for(int i=0;i<cards.length;i++)
			if (cards[i]!=null  && 
				cards[i].intersection(coord) &&
				(rv==null || (cards[i].higherThan(rv))))
				rv = cards[i];
		return rv;
	}

}
